;; The first three lines of this file were inserted by DrScheme. They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(planet plai/plai:1:3/lang/reader)

(define precisao 0.00000000000001)

(define (raiz3 x) 
  
  (define (perto? chute chute-antes)
    (< (abs (- 1 (/ chute chute-antes))) precisao))
  
  (define (melhorar chute)
    (/ (+ (/ x (* chute chute)) (* 2 chute)) 3))
  
  (define (estimar chute chute-antes)
    (if (perto? chute chute-antes) 
        chute
        (estimar (melhorar chute) chute)))
  (estimar 1 x))

;;;;;;;;;;;;;;; testes

(test-inexact-epsilon precisao)
(print-only-errors #t)

(define (proximo? a)
  (> precisao (abs (- 1 (/ (expt a (/ 1. 3)) (raiz3 a))))))
 
(test (raiz3 1.0) 1.0)
(test (raiz3 8.0) 2.0)
(test (raiz3 27.0) 3.0)
; Decimal expansion of cube root of 2.
; On-Line Encyclopedia of Integer Sequences
; http://www.research.att.com/~njas/sequences/A002580
(test (raiz3 2) 1.2599210498948731647672106072782283505702514) 

(test/pred (* 10.0 precisao) proximo?)
(test/pred (* 2.0 precisao) proximo?)
(test/pred precisao proximo?)
(test/pred 1e49 proximo?)
(test/pred 1e48 proximo?)
(test/pred 1e285 proximo?)  ; o maior valor que passou
(test/pred 1e-322 proximo?) ; o menor valor que passou


(include "test-summary.scm")